package com.soulmate.user.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import common.pojo.User;
import common.utils.MD5Util;
import common.utils.MapperUtil;
import com.soulmate.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper = null;

    /*@Autowired
    private Jedis jedis=null;*/
   /* @Autowired
    private ShardedJedisPool pool=null;*/
   @Autowired
    private JedisCluster jedis;

    @Override
    public void checkUserName(String userName) {
        Integer integer = userMapper.checkUserName(userName);
        if (integer >= 1) {
            throw new RuntimeException("用户已存在！");
        }
    }

    @Override
    public void addUserName(User user) {
        try {
            //生成userId
            String userId = UUID.randomUUID().toString();
            user.setUserId(userId);
            String password = user.getUserPassword();
            String password_md5 = MD5Util.md5(password);
            user.setUserPassword(password_md5);
            userMapper.addUserName(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }


    @Override
    public String login(User user) {
        //获取连接池资源 shardedJedis操作3个redis资源
        /* ShardedJedis jedis=pool.getResource();*/
         /*
            1.判断是否合法 密码加密,使用user对象拼接sql
            select * from t_user where user_name=#{userName} and
            user_password=#{userPassword}
            2.通过返回值判断合法,有值说明合法,null登录失败
            3.登录合法
                3.1 创建userJson ObjectMapper转化json
                3.2 生成key值,使用jedis对象存储6379
            4.ticket返回
         */
        //通过加密的密码执行sql判断合法
        String userPassword = user.getUserPassword();
        String userPassword_md5 = MD5Util.md5(userPassword);
        user.setUserPassword(userPassword_md5);
        try {
            //持久化查询存在
            User existUser = userMapper.login(user);
            if (existUser == null) {
                //登录失败
                throw new RuntimeException("登录失败");
            }
            //判断是否已存在一个登陆的ticket
            String userLoginKey = "user_login_" + user.getUserName();
            //登录成功，封装key value存储redis
            String ticket = "EM_TICKET_" + System.currentTimeMillis() + user.getUserName();
            if (jedis.exists(userLoginKey)) {
                //有人登陆，实现顶替逻辑
                //获取登陆过的ticket，删除
                jedis.del(jedis.get(userLoginKey));
            }
            //存储2个key-value
            jedis.setex(userLoginKey, 60 * 60 * 2, ticket);
            String userJson = MapperUtil.MP.writeValueAsString(existUser);
            //超过2小时
            jedis.setex(ticket, 60 * 60 * 2, userJson);
            return ticket;

        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("登录失败");
        }/*finally {
            jedis.close();
        }*/
    }

    @Override
    public String queryUserJson(String ticket) {
        /*ShardedJedis jedis=pool.getResource();*/
        String username = ticket.substring(23);
        Long leftTime = jedis.pttl(ticket);
        if (leftTime < 1000 * 60 * 20) {
            //说明剩余时间达到即将超时
            //将时间延续30分钟
            jedis.pexpire("user_loin_" + username, leftTime + 1000 * 60 * 30);
            jedis.pexpire(ticket, leftTime + 1000 * 60 * 30);
        }
        String userJson = jedis.get(ticket);
        /*jedis.close();*/
        return userJson;
    }

    @Override
    public void logout(String ticket) {
        /*ShardedJedis jedis=pool.getResource();*/
        //1.干掉cookie   ---delCookie
        //2.干掉redis的ticket  ---jedis.del(ticket);
        String username = ticket.substring(23);
        System.out.println(username);
        jedis.del("user_login_" + username);
        jedis.del(ticket);
        /*jedis.close();*/
    }
}
